#include "projwnd.h"

ProjWnd::ProjWnd(QWidget *p) : QFrame(p) {
    this->setObjectName("ProjWnd");
    initUI();
}

ProjWnd::~ProjWnd() {}

void ProjWnd::initUI() {
    _mainVbLayout = new QVBoxLayout;
    _mainVbLayout->setContentsMargins(1, 1, 1, 1);
    _addNewGroupBtn = new QPushButton(tr("Add New Group"), this);
    _mainVbLayout->addWidget(_addNewGroupBtn);
    this->setLayout(_mainVbLayout);

    connect(_addNewGroupBtn, &QPushButton::clicked, this, &ProjWnd::addEmptyGroup);
}

void ProjWnd::addNewProjGroup(QJsonObject obj) {
    ProjGroup *newGp = new ProjGroup(this);
    connect(newGp, &ProjGroup::removeGroup, this, &ProjWnd::removeGroup);
    auto gpName = obj.find("Name")->toString();
    newGp->setGroupName(gpName);
    auto itemList = obj.find("ItemList")->toArray();
    for (int i = 0; i < itemList.size(); i++) {
        newGp->addProjItem(itemList.at(i).toObject().find("Path")->toString());
    }

    int count = _mainVbLayout->count();
    auto rmWidget = static_cast<QPushButton*>(_mainVbLayout->itemAt(count - 1)->widget());
    _mainVbLayout->removeWidget(rmWidget);
    _mainVbLayout->addWidget(newGp);
    _mainVbLayout->addWidget(_addNewGroupBtn);
    _projGpList.append(newGp);
}

void ProjWnd::addEmptyGroup() {
    QLabel ll;
    ProjGroup *newGp = new ProjGroup(this);
    connect(newGp, &ProjGroup::removeGroup, this, &ProjWnd::removeGroup);
    newGp->setGroupName(tr("New Group"));
    int count = _mainVbLayout->count();
    auto rmWidget = static_cast<QPushButton*>(_mainVbLayout->itemAt(count - 1)->widget());
    _mainVbLayout->removeWidget(rmWidget);
    _mainVbLayout->addWidget(newGp);
    _mainVbLayout->addWidget(_addNewGroupBtn);
    _projGpList.append(newGp);
}

void ProjWnd::removeGroup(ProjGroup *rmGp) {
    auto index = _projGpList.indexOf(rmGp);
    if (index == -1) { return; }
    _projGpList.removeAt(index);
    index = _mainVbLayout->indexOf(static_cast<QWidget*>(rmGp));
    if (index == -1) { return; }
    rmGp->deleteLater();
    rmGp = nullptr;

    QList<QWidget *> list;
    for (int i = index + 1; i < _mainVbLayout->count(); i++) {
        list.append(_mainVbLayout->itemAt(i)->widget());
    }
    _mainVbLayout->removeWidget(_mainVbLayout->itemAt(index)->widget());
    for (int i = 0; i < list.size(); i++) {
        _mainVbLayout->addWidget(list.at(i));
    }
}

QJsonObject ProjWnd::getJsonData() {
    QJsonObject obj;
    QJsonArray jsonArr;
    for (int i = 0; i < _projGpList.size(); i++) {
        jsonArr.append(_projGpList.at(i)->getJsonData());
    }
    obj["ProjGroupList"] = jsonArr;
    return obj;
}